package cn.jxufe.imp;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.hibernate.engine.spi.SessionOwner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jxufe.bean.ChatUser;
import cn.jxufe.bean.EasyUIData;
import cn.jxufe.bean.EasyUIDataPageRequest;
import cn.jxufe.bean.Message;
import cn.jxufe.dao.SeedBagDAO;
import cn.jxufe.dao.UserDAO;
import cn.jxufe.entity.SeedBag;
import cn.jxufe.entity.User;
import cn.jxufe.service.UserService;

@Service
public class UserImp implements UserService{
	@Autowired
	UserDAO userDAO;
	
	@Autowired
	SeedBagDAO seedBagDAO;
	
	@Override
	public EasyUIData<User> getList(String userName, EasyUIDataPageRequest easyUIDataPageRequest) {
		EasyUIData<User> result = new EasyUIData<User>();
		List<Sort.Order> orders = new ArrayList<Sort.Order>();
		if(easyUIDataPageRequest.getOrder().equals("asc")) {
            orders.add(new Sort.Order(Direction.ASC, easyUIDataPageRequest.getSort()));
        }else {
            orders.add(new Sort.Order(Direction.DESC, easyUIDataPageRequest.getSort()));
        }
		
		Pageable pageRequest = new PageRequest(
				easyUIDataPageRequest.getPage() - 1, 
				easyUIDataPageRequest.getRows(), 
				new Sort(orders)); ;
		
		Page<User> curpage;
		// seed_name为默认值"doNothing"时，按照pageRequest查找所有内容
		if(userName.equals("doNothing")) {
			curpage = userDAO.findAll(pageRequest);
		}else{
			curpage = userDAO.findByUserNameContaining(userName, pageRequest);
		}
		
		result.setRows(curpage.getContent());
		result.setTotal(curpage.getTotalElements());
		return result;
	}

	@Override
	public Message save(HttpSession session, User user) {
		Message message = new Message();
		try {
			userDAO.save(user);
			message.setCode(0);
			message.setMsg("数据保存成功");
			User curUser = (User) session.getAttribute("curUser");
			if(curUser.getId() == user.getId()) {
				System.out.println("当前用户被修改");
				session.setAttribute("curUser", user);
			}
		}catch(Exception e) {
			e.printStackTrace();
			/*
			 * message.setCode(1); message.setMsg("数据保存错误");
			 */
		}
		return message;
	}
	
	@Override
	public Message updateUser(HttpSession session, User user) {
		
		Message message = new Message();
		try {
			userDAO.save(user);
			// 判断当前被修改的用户是否是curUser
			User curUser = (User) session.getAttribute("curUser");
			if(curUser.getId() == user.getId()) {
				// 由于修改了当前登录的用户的信息，则需要修改curUser
				session.setAttribute("curUser", user); 
				// 1表示修改的是当前登录的用户
				message.setCode(1);  
			}else {
				message.setCode(0);
			}
			message.setMsg("数据保存成功");
		}catch(Exception e) {
			e.printStackTrace();
			message.setCode(0);
			message.setMsg("数据保存错误");
		}
		return message;
	}

	@Override
	@Transactional
	public Message delete(HttpSession session, User user) {
		String result = "OK";
		Message message = new Message();
		try {
			User curUser = (User) session.getAttribute("curUser");
			if(curUser.getId() == user.getId()) {
				message.setCode(0);
				message.setMsg("不能删除自己！");
			}else {
				List<SeedBag> seedBags = seedBagDAO.findByUserId((int)user.getId());
				for (SeedBag seedBag : seedBags) {
					seedBagDAO.delete(seedBag);
				}
				userDAO.delete(user);
				message.setCode(0);
				message.setMsg("数据删除成功!");
			}
		}catch (Exception e) {
			e.printStackTrace();
			message.setCode(1);
			message.setMsg("您还未登录！");
		}
		return message;
	}

	@Override
	public List<User> list() {
		return userDAO.findAll();
	}

	@Override
	public Message setCurUser(HttpSession session, User user) {
		User curUser = new User();
		curUser = userDAO.findOne(user.getId());
		session.setAttribute("curUser", curUser);
		
		ChatUser chatUser = new ChatUser(curUser.getUserName());
		session.setAttribute("chatUser", chatUser);
		
		Message msg = new Message();
		msg.setCode(0);
		msg.setMsg("当前用户已经设定为：" + curUser.getNickName());
		return msg;
	}

	@Override
	public User getUser(User user) {
		return userDAO.findOne(user.getId());
	}


}
